$(function() {
	
	$.sound.enabled = false;
		
	var resultForm = document.forms['resultats'];
	var inGame = true;

	// Preload images
	var teteL = new Array("b","f","g","o","p","r","w","y");
	for (i=0; i<teteL.length; i++) {
		$("<img>").attr("src", 'images/pions/tete'+teteL[i]+'.png');
	}
	$("<img>").attr("src", 'images/board/board-valider-over.png');
	$("<img>").attr("src", 'images/board/board-recommencer.png');
	$("<img>").attr("src", 'images/board/board-recommencer-over.png');
	$("<img>").attr("src", 'images/board/board-result-halfvalid.png');
	$("<img>").attr("src", 'images/board/board-result-valid.png');
	
	//message a l'utilisateur
	function messagePirate(message){
		var options = {};
		$("#bullepirate").effect("slide", options, 500, callback);
		$("#bullepirate").html('<p>'+message+'<br /></p>');
	}
	
	//animation de la bulle du message utilisateur
	function callback(){
		setTimeout(function(){
			$("#bullepirate:hidden").removeAttr('style').hide().fadeIn();
		}, 1000);
	};
	
	//cache la bulle
	$(".cacher_bulle").click(function() {
		$("#bulle").slideUp();
	});
	
	//active / desactive le sons
	$("#soundOnOff").click(function() {
		$.sound.enabled = !$.sound.enabled;
		$(this).css("background-image", $.sound.enabled ? "url('images/board/board-unmute.png')" : "url('images/board/board-mute.png')");
		$(this).html( $.sound.enabled ? "<p class=\"soundOnOff-text\">Activ&eacute;</p>" : "<p class=\"soundOnOff-text\">D&eacute;sactiv&eacute;</p>" );
	})
	
	$("#imgaccroche").click(function() {
		if ($("#bulle:hidden").length!=0) {
			$("#bulle").slideDown();
		}
		else {
			$("#bulle").slideUp();
		}
	});
	
	//action sur le bouton valider
	$("#valider").mouseover(function() {
		if(inGame){
			$(this).css("background-image","url('images/board/board-valider-over.png')");
		}else{
			$(this).css("background-image","url('images/board/board-recommencer-over.png')");
		}
	});
	
	//action sur le bouton valider
	$("#valider").mouseout(function() {
		if(inGame){
			$(this).css("background-image","url('images/board/board-valider.png')");
		}else{
			$(this).css("background-image","url('images/board/board-recommencer.png')");
		}
	});
	
	//action sur le bouton valider
	$("#valider").click(function() {
		if(inGame){
			if(complete()){
				var currGame = resultForm.s1.value+resultForm.s2.value+resultForm.s3.value+resultForm.s4.value;
				checkGame(currGame, updateGame);
				$('#wait').show();
			}else{
				messagePirate("Alors moussaillon !<br />On se défile ?<br />Je suis trop fort pour toi peut être ?");
			}
		}else{
			document.location.href='mastermind.html';
		}
	});
	
	//test si la ligne est complete  
	function complete(){
		var result=1;
		if(resultForm.s1.value == "")
			result=0;
		if(resultForm.s2.value == "")
			result=0;
		if(resultForm.s3.value == "")
			result=0;
		if(resultForm.s4.value == "")
			result=0;
		return result;
	}
	
	//met a jour le jeux
	function updateGame(reponseTbl){
		if(reponseTbl[4] == 'badcheatdetect'){
			messagePirate('alors on triche ?\nPour la peine... On repart a zero !\nChut ! C\'est moi le maître ici');
			clearSaisie();
			stopdraganddrop();
			stopGame();
		}else if(reponseTbl[4] == 'WHAT ?'){
			messagePirate('Il y a un problème avec le jeu.\nLa partie doit redémarer...');
			clearSaisie();
			stopdraganddrop();
			stopGame();
		}else{
			var elem = new Array("","","","","");
			elem[1]=resultForm.s1.value;
			elem[2]=resultForm.s2.value;
			elem[3]=resultForm.s3.value;
			elem[4]=resultForm.s4.value;
			var tour = reponseTbl[1]-1;
			for (i=1; i<5; i++) {
				$("#l"+tour+"t"+i).html('<img src="images/pions/tete'+elem[i]+'.png" alt="pions '+elem[i]+'" />');
			}
			var bienplace = parseInt(reponseTbl[2]);
			for(i=1; i<=bienplace; i++){
				$("#r"+tour+"t"+i).html('<img src="images/board/board-result-valid.png" alt="pions bien place" title="pions bien place" />');
			}
			var malplace = parseInt(reponseTbl[3]);
			for(i=bienplace+1; i<=bienplace+malplace; i++){
				$("#r"+tour+"t"+i).html('<img src="images/board/board-result-halfvalid.png" alt="pions mal place" title="pions mal place" />');
			}
			
			if(reponseTbl[2]=="4" && reponseTbl[3]=="0"){
				messagePirate("Nooooon !!!<br />Je suis vaincu<br />*slurggg*");
				stopdraganddrop();
				stopGame();
			}else if(parseInt(reponseTbl[1])>=13){
				var rep = reponseTbl[5];
				var messFini = "La partie est fini petit !<br />Je suis encore le maître *Mouahahaha*";
				afficheSolution(rep);
				messagePirate(messFini);
				$.sound.play('medias/mouahaha.wav');
				clearSaisie();
				stopdraganddrop();
				stopGame();
			}else{
				messagePirate(''+reponseTbl[4]);
				clearSaisie();
			}
		}
		
		$('#wait').hide();
	}
	
	//efface la saisie précédente de l'utilisateur
	function clearSaisie(){
		for (i=1; i<5; i++) {
			$("#s"+i).html('');
		}
		resultForm.s1.value="";
		resultForm.s2.value="";
		resultForm.s3.value="";
		resultForm.s4.value="";
	}
	
	//arrete le jeu
	function stopGame(){
		inGame=false;
		$("#valider").css("background-image","url('images/board/board-recommencer.png')");
	}
	
	//affichage de la solution
	function afficheSolution(rep){
		$(".saisietrou").css("background-image","none");
		$("#solution").css("background-color","#0D0E0A");
		var listRepPions = '<span class="text-solution">Solution : </span>';
		for (i=0; i<rep.length && i < 4; i++) {
			listRepPions += '<img src="images/pions/tete'+rep[i]+'.png" alt="pions '+rep[i]+'" />&nbsp;';
		}
		$("#solution").html(listRepPions);
	}
	
	//arret du Drag and drop
	function stopdraganddrop(){
		$("#w").draggable('destroy');
		$("#b").draggable('destroy');
		$("#y").draggable('destroy');
		$("#p").draggable('destroy');
		$("#o").draggable('destroy');
		$("#f").draggable('destroy');
		$("#r").draggable('destroy');
		$("#g").draggable('destroy');
		$("#s1").droppable('destroy');
		$("#s2").droppable('destroy');
		$("#s3").droppable('destroy');
		$("#s4").droppable('destroy');
	}
	
	
	//création du drag sur les tetes
	$("#w").draggable({ revert: true, start: function(event, ui) { $.sound.play('medias/cris.wav'); }});
	$("#b").draggable({ revert: true, start: function(event, ui) { $.sound.play('medias/cris.wav'); }});
	$("#y").draggable({ revert: true, start: function(event, ui) { $.sound.play('medias/cris.wav'); }});
	$("#p").draggable({ revert: true, start: function(event, ui) { $.sound.play('medias/cris.wav'); }});
	$("#o").draggable({ revert: true, start: function(event, ui) { $.sound.play('medias/cris.wav'); }});
	$("#f").draggable({ revert: true, start: function(event, ui) { $.sound.play('medias/cris.wav'); }});
	$("#r").draggable({ revert: true, start: function(event, ui) { $.sound.play('medias/cris.wav'); }});
	$("#g").draggable({ revert: true, start: function(event, ui) { $.sound.play('medias/cris.wav'); }});

	//création du drop sur la ligne de saisie
	$("#s1").droppable({
		accept: '#list-img > img',
		drop: function(event, ui) {
			$(this).html('<img class="teteimg" src="images/pions/tete'+ui.draggable.attr("id")+'.png" alt="pions '+ui.draggable.attr("id")+'" />');
			resultForm.s1.value = ui.draggable.attr("id");
		}
	});
	$("#s2").droppable({
		accept: '#list-img > img',
		drop: function(event, ui) {
			$(this).html('<img class="teteimg" src="images/pions/tete'+ui.draggable.attr("id")+'.png" alt="pions '+ui.draggable.attr("id")+'" />');
			resultForm.s2.value = ui.draggable.attr("id");
		}
	});
	$("#s3").droppable({
		accept: '#list-img > img',
		drop: function(event, ui) {
			$(this).html('<img class="teteimg" src="images/pions/tete'+ui.draggable.attr("id")+'.png" alt="pions '+ui.draggable.attr("id")+'" />');
			resultForm.s3.value = ui.draggable.attr("id");
		}
	});
	$("#s4").droppable({
		accept: '#list-img > img',
		drop: function(event, ui) {
			$(this).html('<img class="teteimg" src="images/pions/tete'+ui.draggable.attr("id")+'.png" alt="pions '+ui.draggable.attr("id")+'" />');
			resultForm.s4.value = ui.draggable.attr("id");
		}
	});
	
	// On load :
	$("#bulle").hide();
    checkGame(null, updateGame);
});